package com.yuanss.backenddemo.service.impl;

import com.yuanss.backenddemo.common.Menu;
import com.yuanss.backenddemo.common.R;
import com.yuanss.backenddemo.constant.Constant;
import com.yuanss.backenddemo.constant.MenuConstant;
import com.yuanss.backenddemo.dao.SysMenuDao;
import com.yuanss.backenddemo.dao.SysRoleDao;
import com.yuanss.backenddemo.dao.SysRoleMenuDao;
import com.yuanss.backenddemo.dao.SysUserRoleDao;
import com.yuanss.backenddemo.entity.po.SysMenu;
import com.yuanss.backenddemo.entity.po.SysRole;
import com.yuanss.backenddemo.service.SysMenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yuanss
 * @version 1.0
 * @description 系统菜单服务实现层
 * @date 2024/6/15 22:16:09
 */
@Service
@Slf4j
public class SysMenuServiceImpl implements SysMenuService {

    @Resource
    private SysMenuDao sysMenuDao;

    @Resource
    private SysUserRoleDao sysUserRoleDao;

    @Resource
    private SysRoleMenuDao sysRoleMenuDao;

    @Resource
    private SysRoleDao sysRoleDao;

    @Override
    public R treeMenuByUserId(Long userId) {
        List<Long> roleIds = sysUserRoleDao.queryRoleIdByUserId(userId);
        // 过滤掉已暂停的角色
        List<SysRole> roles = sysRoleDao.queryByIds(roleIds);
        if(roles.isEmpty()){
            return R.success("获取菜单列表为空");
        }
        List<Long> filterRoleList = roles.stream().
                filter(role -> Constant.status.NORMAL.equals(role.getStatus()))
                .map(SysRole::getRoleId)
                .collect(Collectors.toList());
        List<Long> menuIds = sysRoleMenuDao.queryMenuIdByRoleIds(filterRoleList);
        List<SysMenu> menus = sysMenuDao.listByMenuIds(menuIds);
        // 存在只有子目录id，无父目录id的情况，需要特殊处理
        // 将menus中父目录id放到set中
        List<Long> parentIds = menus.stream().
                map(SysMenu::getParentId).distinct().
                collect(Collectors.toList());
        parentIds.forEach(parentId -> {
            if(!MenuConstant.ROOT_MENU_ID.equals(parentId)
                && !menuIds.contains(parentId)
            ){
                menuIds.add(parentId);
            }
        });
        menus = sysMenuDao.listByMenuIds(menuIds);
        if(menus.isEmpty()){
            return R.success("获取菜单列表为空");
        }
        List<Menu> builtMenuTree = Menu.SysMenuToMenuTree(menus);
        return R.success("获取菜单列表成功", builtMenuTree);
    }

    @Override
    public R treeMenu() {
        // todo 菜单分目录、菜单、以及按钮，权限控制更细节一点
        List<SysMenu> menus = sysMenuDao.queryAll();
        if(menus.isEmpty()){
            return R.success("获取菜单列表为空");
        }
        List<Menu> builtMenuTree = Menu.SysMenuToMenuTree(menus);
        return R.success("获取菜单列表成功", builtMenuTree);
    }
}
